package com.example.demo.controller;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import com.example.demo.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.security.SignatureException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangyx
 * @desc
 * @date 2020/8/11 9:24
 **/
@RestController
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/user/login")
    public Map<String,Object> login(User user){
        Map<String,Object> map = new HashMap<>();
        try {
            User userdb = userService.getUser(user);
            Map<String,String> payload = new HashMap<>();
            payload.put("id",String.valueOf(userdb.getId()));
            payload.put("username",userdb.getUsername());
            String token = JWTUtils.getToken(payload);
            map.put("token",token);
            map.put("state",true);
            map.put("msg","登陆成功");
        }catch (Exception e){
            map.put("state",true);
            map.put("msg",e.getMessage());
        }
        return map;
    }

    @PostMapping("/user/get")
    public Map<String, Object> getUser(String token){
        Map<String,Object> map = new HashMap<>();
        DecodedJWT verify = JWTUtils.getTokenInfo(token);
        String username = verify.getClaim("username").asString();
        map.put("id",verify.getClaim("id").asString());
        map.put("username",verify.getClaim("username").asString());
        return map;
    }
}
